package com.kai.service.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


public class SHAUtil {

    private static final String SHA_1 = "SHA-1";

    private static final String SHA_256 = "SHA-256";

    private static String getMessageDigest(String algorithm, String s) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.update(s.getBytes(StandardCharsets.UTF_8));

            return byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 字符串SHA1加密
     *
     * @param s 要加密的字符串
     * @return 加密后的字符串
     */
    public static String getSHA1(String s){
        return getMessageDigest(SHA_1, s);
    }

    /**
     * 字符串SHA256加密
     *
     * @param s 要加密的字符串
     * @return 加密后的字符串
     */
    public static String getSHA256(String s){
        return getMessageDigest(SHA_256, s);
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes 字节数组
     * @return 16进制字符串
     */
    private static String byte2Hex(byte[] bytes){
        StringBuilder stringBuilder = new StringBuilder();
        String temp;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                // 1得到一位的进行补0操作
                stringBuilder.append("0");
            }
            stringBuilder.append(temp);
        }
        return stringBuilder.toString();
    }

    /**
     * 生成32位随机盐
     *
     * @return 32位随机数
     */
    public static String generateSalt() {
        return byte2Hex(new SecureRandom().generateSeed(16));
    }

}

